package com.nekonomics
package domain.auxiliary

import zio.*

import java.time.*
import java.time.format.DateTimeFormatter

case class PayCallback(
  orderId: Long,
  tradeNo: String,
  paidAt: OffsetDateTime
)


object PayCallback {
  def of(params: Map[String, String]) = {
    for {
      orderId <- ZIO.succeed(params.get("out_trade_no")).someOrFail(new RuntimeException("缺少out_trade_no")).map(_.toLong)
      tradeNo <- ZIO.succeed(params.get("trade_no")).someOrFail(new RuntimeException("缺少trade_no"))
      payTimeStr <- ZIO.succeed(params.get("gmt_payment")).someOrFail(new RuntimeException("缺少gmt_payment"))
      localTime <- ZIO.attempt(LocalDateTime.parse(payTimeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
      paidAt = OffsetDateTime.of(localTime, ZoneOffset.ofHours(8))
    } yield PayCallback(orderId, tradeNo, paidAt)
  }
}
